#include "py_mqtt.h"

#include "Log.h"

PyMQTTIO::PyMQTTIO(const char *id)
	: mosquittopp(id)
	, link(false) 
	, sub_s("P1075605")
	, rec_queue(new QueueData<std::string>("mqtt_rec_queue"))
	, rep_queue(new QueueData<std::string>("mqtt_rep_queue"))
{
};

void PyMQTTIO::on_connect(int rc) 
{ 
#ifdef _DEBUG
	std::cout << "on_connect:"<< rc << std::endl; 
#endif
	if (0 == rc) {
		int ret = subscribe(NULL, sub_s.c_str());
		if (MOSQ_ERR_SUCCESS != ret)
		{
			CLogger::createInstance()->Log(MsgInfo
				, "subscribe %s error!", sub_s.c_str());
		}
	}
};
void PyMQTTIO::on_disconnect() 
{ 
#ifdef _DEBUG
	std::cout << "on_disconnect" << std::endl; 
#endif
	int ret = unsubscribe(NULL, sub_s.c_str());
	if (MOSQ_ERR_SUCCESS != ret)
	{
		CLogger::createInstance()->Log(MsgInfo
			, "unsubscribe %s error!", sub_s.c_str());
	}
};
void PyMQTTIO::on_publish(int mid) 
{ 
#ifdef _DEBUG
	std::cout << "on_publish:"<< mid << std::endl; 
#endif
};

void PyMQTTIO::on_subscribe(int mid, int qos_count, const int *granted_qos)
{
#ifdef _DEBUG
	std::cout<< "订阅 mid: "<<mid<< std::endl;
#endif
}
void PyMQTTIO::on_message(const struct mosquitto_message *message)
{
	bool ret = false;
	mosqpp::topic_matches_sub(sub_s.c_str(), message->topic, &ret);
	if (ret)
	{
		std::string strRcv = std::string((char *)message->payload,message->payloadlen);
		rec_queue->add(strRcv);
#ifdef _DEBUG
		std::cout << "来自:" << message->topic << "的消息:" << strRcv.length() << std::endl;
		for (int i = 0; i < strRcv.length(); i++)
		{
			printf("%02hhx ", (char)strRcv.at(i));
		}
		printf("\n");
#endif // DEBUG
	}
}

bool PyMQTTIO::pop_rec(std::string &it)
{
	return rec_queue->pop(it);
}

void PyMQTTIO::add_rep(std::string it)
{
	rep_queue->add(it);
}

bool PyMQTTIO::pop_rep(std::string &it)
{
	return rep_queue->pop(it);
}
